package com.hbx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbx.aspect.annotation.SensitiveFilter;
import com.hbx.model.ResourceType;
import com.hbx.service.ResourceTypeService;
import com.hbx.utils.Result;
import com.hbx.vo.res.ResTypeVo;
import com.hbx.vo.res.insertOrUpdateResTypeDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hbx
 * @since 2022-02-12
 */
@RestController
@RequestMapping("/restype")
@Api(tags = "资源分类处理器")
public class ResourceTypeController {

    @Autowired
    private ResourceTypeService resourceTypeService;

    @RequestMapping(value = "/getTypeList",method = RequestMethod.GET)
    @ApiModelProperty("获得分类列表")
    public Result getTypeList(){
        Result r = new Result();
        QueryWrapper<ResourceType> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        List<ResourceType> list = resourceTypeService.list(wrapper);
        List<ResTypeVo> resTypeVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)){
            list.stream().forEach(res -> {
                ResTypeVo vo = new ResTypeVo();
                BeanUtils.copyProperties(res, vo);
                resTypeVos.add(vo);
            });
        }
        r.setCode(200).setData(resTypeVos);
        return r;
    }

    @RequestMapping(value = "/insertOrUpdateResType",method = RequestMethod.POST)
    @ApiModelProperty("添加或修改分类")
    @SensitiveFilter
    public Result insertOrUpdateResType(@RequestBody @Valid insertOrUpdateResTypeDto dto, BindingResult result){
        Result r = new Result();
        if (result.hasErrors()){
            r.setCode(400).setMsg(result.getFieldError().getDefaultMessage());
            return r;
        }
        resourceTypeService.insertOrUpdateResType(dto, r);
        return r;
    }

    @RequestMapping(value = "/removeType",method = RequestMethod.GET)
    @ApiModelProperty("删除分类")
    public Result removeType(@RequestParam("resTypeId") Integer resTypeId){
        Result r = new Result();
        if (resTypeId == null){
            r.setCode(400).setMsg("resTypeId为必传项");
            return r;
        }
        resourceTypeService.removeType(resTypeId, r);
        return r;
    }
}

